package com.zerone.dy.demomsg.webSocket.config;

import com.zerone.common.constant.TokenHeader;
import com.zerone.common.redis.service.RedisService;
import com.zerone.common.utils.JwtTokenUtile;
import com.zerone.common.utils.JwtUtils;
import com.zerone.dy.demomsg.webSocket.constant.WebSocketConstant;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpoint;
import javax.websocket.server.ServerEndpointConfig;
import java.util.List;
import java.util.Map;

@Configuration
public class WebSocketConfig extends ServerEndpointConfig.Configurator
{
    @Value("${jwt.key}")
    private String key;
    @Value("${jwt.timeOut}")
    private int timeOut;
    @Value("${auth.sso.enable:true}")
    private boolean authSSOEnable;

    @Autowired
    private RedisService redisService;


    @Bean
    @Scope("prototype")
    public JwtUtils newJwt() {
        JwtUtils jjwtUtil = new JwtUtils(key, timeOut);
        return jjwtUtil;
    }

    @Bean
    @Scope("prototype")
    public JwtTokenUtile newjwtUtile() {
        return new JwtTokenUtile(redisService, newJwt());
    }

    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }


    // 重写这个方法，可以修改客户端与服务端建立连接时的配置信息
    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response)
    {
        Map<String, List<String>> headers = request.getHeaders();
        final Map<String,Object> userProperties = sec.getUserProperties();
        String token = headers.get(TokenHeader.ADMIN_HEADER_TOKEN_KEY).get(0);

        // 可以往HttpSession中添加属性
        if(StringUtils.isNotBlank(token)){
            Claims claims = newjwtUtile().vaildToken(token, authSSOEnable);
            String username = claims.get("userAccount", String.class);
            userProperties.put(WebSocketConstant.AC_NO, username);
        }


    }
}
